package com.daykw.wkinfo.task;

import java.util.List;

import org.apache.log4j.Logger;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;

import com.alibaba.druid.pool.DruidDataSource;
import com.daykw.wkinfo.utils.EhcacheUtils;
import com.daykw.wkinfo.utils.IPPoolMap;

public class ArticleIpPoolTask implements Runnable {
	private static Logger logger = Logger.getLogger(ArticleIpPoolTask.class);
	public static Dao taskDao;
	{
		DruidDataSource dataSource = new DruidDataSource();

		dataSource.setDriverClassName("com.mysql.jdbc.Driver");

		dataSource.setUrl("jdbc:mysql://211.152.47.69:3306/task_center?useUnicode=true&characterEncoding=UTF-8");

		dataSource.setUsername("new_root");
		dataSource.setPassword("@Hyipsos");
		dataSource.setTestOnBorrow(true);
		dataSource.setTestOnReturn(true);
		dataSource.setTestWhileIdle(true);
		dataSource.setValidationQuery("SELECT 1 ");
		taskDao = new NutDao(dataSource);
	}

	@Override
	public void run() {
		try {
			// logger.info("******************************************************************");
			// logger.info("******************************************************************");
			logger.info("***********ip队列长度:" + IPPoolMap.getAqueue().size() + "****************");
			// logger.info("******************************************************************");
			// logger.info("******************************************************************");
			this.getIpsTask();
		} catch (Exception e) {
			logger.error("", e);
		}

	}

	private void getIpsTask() {

		int tcount = 1000;
		logger.info("***********获取" + tcount + "个IP*************");
		String querySql = "SELECT * FROM 	t_ips WHERE	id >= (	(SELECT MAX(id) FROM t_ips) - (SELECT MIN(id) FROM t_ips)	) * RAND() + (SELECT MIN(id) FROM t_ips) LIMIT "
				+ tcount;
		Sql sql = Sqls.queryRecord(querySql);
		sql.setCallback(Sqls.callback.records());
		
		taskDao.execute(sql);
		List<Record> list = sql.getList(Record.class);

		for (Record ip : list) {
			String ips = ip.getString("ips");
			if (!EhcacheUtils.getInstance().containsKey(ips)) {
				IPPoolMap.getAqueue().offer(ip);
			}

		}
	}

}
